package com.sirdc.modules.sys.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.sirdc.modules.sys.entity.SysLogin;


/**
 * 密码加密
 * @author 彭伟煌(weihuang.peng@imethsoft.com)
 * @version Revision: 1.0.0 Oct 25, 2014
 */
@Service
public class PasswordHelper {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    @Value("${password.hashAlgorithmName}")
    private String hashAlgorithmName = "SHA-256";//默认是md5加密
    
    @Value("${password.hashIterations}")
    private int hashIterations = 2;//默认密码迭代两次

    /**
     * 对用户设置加密钥匙，并对密码进行加密
     * @param user
     */
    public void encryptPassword(SysLogin user) {
        user.setSaltKey(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new SimpleHash(
	        hashAlgorithmName,
	        user.getPassword(),
	        ByteSource.Util.bytes(user.getSaltKey()),
	        hashIterations
        ).toHex();

        user.setPassword(newPassword);
    }
    
    /**
     * 返回加密后的结果
     * @author: weihuang.peng
     * @param password
     * @param salt
     * @return
     */
    public String encryptPassResult(String password, String salt) {
		String newPassword = new SimpleHash(hashAlgorithmName,
				password, 
				ByteSource.Util.bytes(salt),
				hashIterations).toHex();
		return newPassword;
    }
}